package com.yy.tech.inte.service.intercepter;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * technical-identification$
 *
 * @author YY
 * @version 1.0.0
 * @date $ $
 * @description: TODO
 */
@Aspect
@Component
public class InterceptorUtil {
    @Autowired
    private Environment environment;
    @Autowired
    private ApplicationContext context;

    @Around("@annotation(interceptor)")
    public Object intercept(ProceedingJoinPoint point, RestInterceptor interceptor) throws Throwable {
        String condition =interceptor.condition();
        Method method=((MethodSignature)point.getSignature()).getMethod();
        if (!StringUtils.isEmpty(condition)){
            boolean result =environment.getProperty(condition,Boolean.class,interceptor.ifMissing());
            if (result){
                RequestInterceptor ri = null;
                String name = interceptor.interceptorName();
                if (!StringUtils.isEmpty(name)){
                    ri=context.getBean(name,RequestInterceptor.class);
                }else{
                    Class<? extends RequestInterceptor> clz = interceptor.interceptor();
                    if (null != clz){
                        ri=context.getBean(clz);
                    }
                }
                if (null != ri){
                    Class clz= method.getReturnType();
                    return ri.response(clz);
                }
            }
        }
        return  point.proceed();
    }
}
